
<template>
  <div id="main" class="app">
    <div class="divHead">
      <img src="@/images/front/home.png" @click="toUserPage"/>
    </div>
    <div class="divTitle">
      <div class="divStatic">
<!--        <img src="@/images/front/logo.png"  class="logo1"/>-->
        <img :src="imgPathConvert( item.image)"  class="logo1"/>

        <div class="divDesc">
          <div class="divName">{{item.name}}</div>
          <div class="divSend">
            <span><img src="@/images/front/time.png"/> 距离1.5km</span>
            <span><img src="@/images/front/money.png"/> 配送费6元</span>
            <span><img src="@/images/front/location.png"/> 预计时长12min</span>
          </div>
        </div>
      </div>
      <div class="divDesc">
        {{item.jianjie}}
<!--        简介: 菩提阁中餐厅是菩提阁点餐的独立的品牌，定位“大众 化的美食外送餐饮”，旨为顾客打造专业美食。-->
      </div>
    </div>
    <div class="divBody">
      <div class="divType">
        <ul>
          <li v-for="(item,index) in categoryList" :key="index" @click="categoryClick(index,item.id,item.type)" :class="{active:activeType === index}">{{item.name}}</li>
        </ul>
      </div>
      <div class="divMenu">
        <div>
          <div class="divItem" v-for="(item,index) in dishList" :key="index" @click="dishDetails(item)">
            <el-image :src="imgPathConvert(item.image)" >
              <div slot="error" class="image-slot">
                <img src="@/images/front/noImg.png"/>
              </div>
            </el-image>
            <div>
              <div class="divName">{{item.name}}</div>
              <div class="divDesc">{{item.description}}</div>
              <div class="divDesc">{{'月销' + (item.saleNum ? item.saleNum : 0)  }}</div>
              <div class="divBottom"><span>￥</span><span>{{item.price/100}}</span></div>
              <div class="divNum">
                <div class="divSubtract" v-if="item.number > 0">
                  <img src="@/images/front/subtract.png" @click.prevent.stop="subtractCart(item)"/>
                </div>
                <div class="divDishNum">{{item.number}}</div>
                <div class="divTypes" v-if="item.flavors && item.flavors.length > 0 && !item.number " @click.prevent.stop="chooseFlavorClick(item)">选择规格</div>
                <div class="divAdd" v-else>
                  <img src="@/images/front/add.png" @click.prevent.stop="addCart(item)"/>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="divLayer">
      <div class="divLayerLeft"></div>

    </div>
    <div class="divCart" v-if="categoryList.length > 0">
      <div :class="{imgCartActive: cartData && cartData.length > 0, imgCart:!cartData || cartData.length<1}" @click="openCart"></div>
      <div :class="{divGoodsNum:1===1, moreGoods:cartData && cartData.length > 99}" v-if="cartData && cartData.length > 0">{{ goodsNum }}</div>
      <div class="divNum">
        <span>￥</span>
        <span>{{goodsPrice}}</span>
      </div>
      <div class="divPrice"></div>
      <div :class="{btnSubmitActive: cartData && cartData.length > 0, btnSubmit:!cartData || cartData.length<1}" @click="toAddOrderPage">去结算</div>
    </div>
    <van-dialog v-model="dialogFlavor.show" :show-confirm-button="false" class="dialogFlavor" ref="flavorDialog">
      <div class="dialogTitle">{{dialogFlavor.name}}</div>
      <div class="divContent">
        <div v-for="flavor in dialogFlavor.flavors" :key="flavor.id">
          <div class="divFlavorTitle">{{flavor.name}}</div>
          <span v-for="item in JSON.parse(flavor.value)"
                :key="item"
                @click="flavorClick(flavor,item)"
                :class="{spanActive:flavor.dishFlavor === item}"
          >{{item}}</span>
        </div>
      </div>
      <div class="divBottom">
        <div><span class="spanMoney">￥</span>{{dialogFlavor.price/100}}</div>
        <div @click="dialogFlavorAddCart">加入购物车</div>
      </div>
      <div class="divFlavorClose" @click="dialogFlavor.show = false">
        <img src="@/images/front/close.png"/>
      </div>
    </van-dialog>
    <van-popup v-model="cartDialogShow" position="bottom" :style="{ height: '50%' }" class="dialogCart">
      <div class="divCartTitle">
        <div class="title">购物车</div>
        <div class="clear" @click="clearCart">
          <i class="el-icon-delete"></i> 清空
        </div>
      </div>
      <div class="divCartContent">
        <div v-for="item in cartData" :key="item.id" class="divCartItem">
          <el-image :src="imgPathConvert(item.image)" >
            <div slot="error" class="image-slot">
              <img src="@/images/front/noImg.png"/>
            </div>
          </el-image>
          <div class="divDesc">
            <div class="name">{{item.name}}</div>
            <div class="price">
              <span class="spanMoney">￥</span>{{item.amount}}</div>
          </div>
          <div class="divNum">
            <div class="divSubtract">
              <img src="@/images/front/subtract.png" @click="cartNumberSubtract(item)"/>
            </div>
            <div class="divDishNum">{{item.number}}</div>
            <div class="divAdd">
              <img src="@/images/front/add.png" @click="cartNumAdd(item)"/>
            </div>
          </div>
          <div class="divSplit"></div>
        </div>
      </div>
    </van-popup>
    <van-dialog v-model="detailsDialog.show"
                :show-confirm-button="false"
                class="detailsDialog"
                ref="detailsDialog"
                v-if="detailsDialog.show"
    >
      <div class="divContainer">
        <el-image :src="imgPathConvert(detailsDialog.item.image)" >
          <div slot="error" class="image-slot">
            <img src="@/images/front/noImg.png"/>
          </div>
        </el-image>
        <div class="title">{{detailsDialog.item.name}}</div>
        <div class="content">{{detailsDialog.item.description}}</div>
      </div>
      <div class="divNum">
        <div class="left">
          <span>￥</span><span>{{detailsDialog.item.price/100}}</span>
        </div>
        <div class="right">
          <div class="divSubtract" v-if="detailsDialog.item.number > 0">
            <img src="@/images/front/subtract.png" @click="subtractCart(detailsDialog.item)"/>
          </div>
          <div class="divDishNum">{{detailsDialog.item.number}}</div>
          <div class="divTypes" v-if="detailsDialog.item.flavors && detailsDialog.item.flavors.length > 0 && !detailsDialog.item.number " @click ="chooseFlavorClick(detailsDialog.item)">选择规格</div>
          <div class="divAdd" v-else>
            <img src="@/images/front/add.png" @click="addCart(detailsDialog.item)"/>
          </div>
        </div>
      </div>
      <div class="detailsDialogClose" @click="detailsDialog.show = false">
        <img src="@/images/front/close.png"/>
      </div>
    </van-dialog>
    <van-dialog v-model="setMealDialog.show"
                :show-confirm-button="false"
                class="setMealDetailsDialog"
                ref="setMealDetailsDialogd"
                v-if="setMealDialog.show"
    >
      <div class="divContainer">
        <div class="title">{{setMealDialog.item.name}}</div>
        <div class="item" v-for="(item,index) in setMealDialog.item.list.setmealDishes" :key="index">
          <el-image :src="imgPathConvert(item.image)">
<!--          <el-image :src="imgPathConvert('0f252364-a561-4e8d-8065-9a6797a6b1d3.jpg')">-->
            <div slot="error" class="image-slot">
              <img src="@/images/front/noImg.png"/>
            </div>
          </el-image>
          <div class="divSubTitle">{{item.name + '(' + item.copies + '份)' }}
            <div class="divPrice">
              <span>￥</span><span>{{item.price/100}}</span>
            </div>
          </div>
          <div class="content">{{item.description}}</div>
        </div>
      </div>
      <div class="divNum">
        <div class="left">
          <span>￥</span><span>{{setMealDialog.item.price/100}}</span>
        </div>
        <div class="right">
          <div class="divSubtract" v-if="setMealDialog.item.number > 0">
            <img src="@/images/front/subtract.png" @click="subtractCart(setMealDialog.item)"/>
          </div>
          <div class="divDishNum">{{setMealDialog.item.number}}</div>
          <div class="divAdd" v-if="setMealDialog.item.number">
            <img src="@/images/front/add.png" @click="addCart(setMealDialog.item)"/>
          </div>
          <div class="addCart"  @click="addCart(setMealDialog.item)" v-if="!setMealDialog.item.number">加入购物车</div>
        </div>
      </div>
      <div class="detailsDialogClose" @click="setMealDialog.show = false">
        <img src="@/images/front/close.png"/>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import setRem from "@/js/base";
import {addCartApi,categoryListApi,dishListApi,cartListApi,clearCartApi,setMealDishDetailsApi,setmealListApi,updateCartApi} from "@/api/front/main"
import {imgPath} from "@/api/front/common";
export default {
  name: "FontsIndex",
  data(){
    return {
      //左边菜品类别index
      activeType:0,
      categoryList:[],
      categoryId:undefined,
      dishList:[],
      cartData:[],
      dialogFlavor:{
        name:'',
        flavors:[],
        dishId:undefined,
        price:undefined,
        show:false,
        image:''
      },
      cartDialogShow:false,
      detailsDialog:{
        show:false,
        item:{image:''}
      },
      setMealDialog:{
        show:false,
        item:{}
      },
      item:{}
    }
  },
  computed:{
    goodsNum(){
      let num = 0
      this.cartData.forEach(item=>{
        num += item.number
      })
      if(num <99){
        return num
      }else{
        return '99+'
      }
    },
    goodsPrice(){
      let price = 0
      this.cartData.forEach(item=>{
        price += (item.number * item.amount)
      })
      return price
    }
  },
  created(){
    setRem(document, window);
    this.item=JSON.parse(localStorage.getItem("md"));
  },
  watch:{
    'dialogFlavor.show'(flag){
      if(flag){
        document.querySelector('.divCart').style.zIndex = 1
      }else{
        document.querySelector('.divCart').style.zIndex = 3000
      }
    },
  },
  mounted(){
    this.initData()
  },
  methods:{
    //初始化数据
    initData(){
      Promise.all([categoryListApi(),cartListApi({})]).then(res=>{
        //获取分类数据
        if(res[0].code === 1){
          this.categoryList = res[0].data
          if(Array.isArray(res[0].data) && res[0].data.length > 0){
            this.categoryId = res[0].data[0].id
            if(res[0].data[0].type === 1){
              this.getDishList()
            }else{
              this.getSetmealData()
            }
          }
        }else{
          this.$notify({ type:'warning', message:res[0].msg});
        }
        //获取菜品数据
        if(res[1].code === 1){
          this.cartData = res[1].data
        }else{
          this.$notify({ type:'warning', message:res[1].msg});
        }
      })
    },
    //分类点击
    categoryClick(index,id,type){
      this.activeType = index
      this.categoryId = id
      if(type === 1){//菜品
        this.getDishList()
      }else{
        this.getSetmealData()
      }
    },
    //网络图片路径转换
    imgPathConvert(path){
      return imgPath(path)
    },
    //获取菜品数据
    async getDishList(){
      if(!this.categoryId){
        return
      }
      const res = await dishListApi({categoryId:this.categoryId,status:1})
      if(res.code === 1){
        let dishList = res.data
        const cartData  = this.cartData
        if(dishList.length > 0 && cartData.length > 0){
          dishList.forEach(dish=>{
            cartData.forEach(cart=>{
              if(dish.id === cart.dishId){
                dish.number = cart.number
              }
            })
          })
        }
        this.dishList = dishList
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },
    //获取套餐数据setmealId
    async getSetmealData(){
      if(!this.categoryId){
        return
      }
      const res = await setmealListApi({categoryId:this.categoryId,status:1})
      if(res.code === 1){
        let dishList = res.data
        const cartData  = this.cartData
        if(dishList.length > 0 && cartData.length > 0){
          dishList.forEach(dish=>{
            cartData.forEach(cart=>{
              if(dish.id === cart.setmealId){
                dish.number = cart.number
              }
            })
          })
        }
        this.dishList = dishList
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },
    //获取购物车数据
    async getCartData(){
      const res = await cartListApi({})
      if(res.code === 1){
        this.cartData = res.data
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },
    //菜单中往购物车中添加商品
    async addCart(item){
      let params = {
        amount:item.price/100,//金额
        dishFlavor:item.dishFlavor,//口味  如果没有传undefined
        dishId:undefined,//菜品id
        setmealId:undefined,//套餐id
        name:item.name,
        image:item.image
      }
      if(Array.isArray(item.flavors)){//表示是菜品
        params.dishId = item.id
      }else{//表示套餐 套餐没有口味
        params.setmealId = item.id
      }
      const res = await addCartApi(params)
      if(res.code === 1){
        this.dishList.forEach(dish=>{
          if(dish.id === item.id){
            dish.number = res.data.number
          }
        })
        if(this.setMealDialog.show){
          item.number = res.data.number
        }
        this.getCartData()
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },

    //菜单中减少选中的商品
    async subtractCart(item){
      let params = {
        dishId:item.id,
      }
      if(!Array.isArray(item.flavors)){
        params = {
          setmealId:item.id,
        }
      }
      const res = await updateCartApi(params)
      if(res.code === 1){
        this.dishList.forEach(dish=>{
          if(dish.id === item.id){
            dish.number = (res.data.number === 0 ? undefined : res.data.number)
          }
        })
        if(this.setMealDialog.show){
          item.number = (res.data.number === 0 ? undefined : res.data.number)
        }
        this.getCartData()
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },

    //展开购物车
    openCart(){
      if(this.cartData.length > 0){
        this.cartDialogShow = true
      }
    },
    //购物车中增加商品数量
    async cartNumAdd(item){
      let params = {
        amount:item.amount,//金额
        dishFlavor:item.dishFlavor,//口味  如果没有传undefined
        dishId:item.dishId,//菜品id
        setmealId:item.setmealId,//套餐id
        name:item.name,
        image:item.image
      }
      const res = await addCartApi(params)
      if(res.code === 1){
        this.dishList.forEach(dish=>{
          if(dish.id === (item.dishId || item.setmealId)){
            dish.number = res.data.number
          }
        })
        console.log(this.dishList)
        this.getCartData()
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },
    //购物车中减少商品数量
    async cartNumberSubtract(item){
      let params = {
        dishId:item.dishId,
        setmealId:item.setmealId,
      }
      const res = await updateCartApi(params)
      if(res.code === 1){
        this.dishList.forEach(dish=>{
          if(dish.id === (item.dishId || item.setmealId)){
            dish.number = (res.data.number === 0 ? undefined : res.data.number)
          }
        })
        this.getCartData()
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },

    //修改商品列表中的数据number
    changeDishList(item){
      for(let ele of this.dishList){
        if(ele.id === (item.setmealId || item.dishId)){
          ele.number = item.number
        }
      }
    },

    //清空购物车
    async clearCart(){
      const res = await clearCartApi()
      if(res.code === 1){
        for(let ele of this.dishList){
          ele.number = undefined
        }
        this.cartData = []
        this.cartDialogShow = false
      }else{
        this.$notify({ type:'warning', message:res.msg});
      }
    },
    //点击选择规格
    chooseFlavorClick(item){
      this.dialogFlavor = {
        name:'',
        flavors:[],
        dishId:undefined,
        price:undefined,
        show:false
      }
      this.dialogFlavor={
        name:item.name,
        flavors:item.flavors,
        dishId:item.id,
        price:item.price,
        show:true,
        image:item.image
      }
    },
    flavorClick(flavor,item){
      flavor.dishFlavor = item
      //强制刷新dialog的dom
      this.dialogFlavor.show = false
      this.dialogFlavor.show = true
    },
    //选择规格加入购物车
    dialogFlavorAddCart(){
      const dialogFlavor = this.dialogFlavor
      let flag = true
      let dishFlavor = []
      dialogFlavor.flavors.forEach(item=>{
        if(item.dishFlavor){
          dishFlavor.push(item.dishFlavor)
        }else{
          flag = false
          Notify({ type: 'warning', message: '请选择'+ item.name });
        }
      })
      if(flag){
        this.addCart({
          price:dialogFlavor.price,
          dishFlavor:dishFlavor.join(","),
          id:dialogFlavor.dishId,
          flavors:[],
          image:dialogFlavor.image,
          name:dialogFlavor.name
        })
        this.dialogFlavor.show = false
      }

    },
    //跳转到去结算界面
    toAddOrderPage(){
      if(this.cartData.length > 0){
        window.requestAnimationFrame(()=>{
          window.location.href ='#/front/addorder'
        })
      }
    },
    toUserPage(){
      window.requestAnimationFrame(()=>{
        window.location.href= '#/front/page/mendian'
      })
    },
    async dishDetails(item){
      //先清除对象数据，如果不行的话dialog使用v-if
      this.detailsDialog.item = {}
      this.setMealDialog.item = {}
      if(Array.isArray(item.flavors)){
        this.detailsDialog.item = item
        this.detailsDialog.show = true
      }else{
        //显示套餐的数据
        const res = await setMealDishDetailsApi(item.id)
        if(res.code === 1){
          this.setMealDialog.item = {...item,list:res.data}
          console.log(JSON.stringify(this.setMealDialog.item.list))
          this.setMealDialog.show = true
        }else{
          this.$notify({ type:'warning', message:res.msg});
        }
      }

    }

  }
}
</script>

<style scoped lang="less">
//@import "@/styles/front/index.css";
@import "@/styles/front/main.css";
.logo1{
  width: 39rem;
  height: 39rem;
  opacity: 1;
  background: #333333;
  border-radius: 6rem;
  margin-right: 10rem;
}
html,
body {
  //max-width: 750px;
  height: 100%;
  background: #f3f2f7;
  font-family: Helvetica;
  overflow: hidden;
}

html,
body,
h1,
h2,
h3,
h4,
h5,
h6,
p,
ul,
li {
  margin: 0;
  padding: 0;
}

ul,
li {
  list-style: none;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-weight: normal;
}

h3 {
  font-size: 16px;
}

h4 {
  font-size: 14px;
}

p {
  font-size: 12px;
}

em,
i {
  font-style: normal;
}

/*@font-face {*/
/*  font-family: "DIN-Medium";*/
/*  src: url("ttf/DIN-Medium.otf");*/
/*  font-weight: normal;*/
/*  font-style: normal;*/
/*}*/

/*@font-face {*/
/*  font-family: "DIN";*/
/*  src: url("ttf/DIN-Bold.otf");*/
/*  font-weight: normal;*/
/*  font-style: normal;*/
/*}*/

/*@font-face {*/
/*  font-family: "PingFangSC-Regular";*/
/*  src: url("ttf/PingFangSC-Regular.ttf");*/
/*  font-weight: normal;*/
/*  font-style: normal;*/
/*}*/

/*@font-face {*/
/*  font-family: "PingFangSC-Regular";*/
/*  src: url("ttf/PingFangSC-Regular.ttf");*/
/*  font-weight: normal;*/
/*  font-style: normal;*/
/*}*/

/*@font-face {*/
/*  font-family: "PingFangSC-Semibold";*/
/*  src: url("ttf/PingFangSC-Semibold.ttf");*/
/*  font-weight: normal;*/
/*  font-style: normal;*/
/*}*/

.app {
  height: 100%;
}

.van-overlay {
  background-color: rgba(0, 0, 0, 0.3);
}

.van-dialog {
  overflow: inherit;
}

::-webkit-input-placeholder {
  font-size: 13rem;
  /*font-family: PingFangSC, PingFangSC-Regular;*/
  font-weight: 400;
  text-align: left;
  color: #999999;
}

:-moz-placeholder {
  /* Firefox 18- */
  font-size: 13rem;
  /*font-family: PingFangSC, PingFangSC-Regular;*/
  font-weight: 400;
  text-align: left;
  color: #999999;
}
::-moz-placeholder {
  /* Firefox 19+ */
  font-size: 13rem;
  /*font-family: PingFangSC, PingFangSC-Regular;*/
  font-weight: 400;
  text-align: left;
  color: #999999;
}

:-ms-input-placeholder {
  font-size: 13rem;
  /*font-family: PingFangSC, PingFangSC-Regular;*/
  font-weight: 400;
  text-align: left;
  color: #999999;
}

</style>
